package com.jason.demo.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RestController
public class FileUploadController {
	
	/**
	 * 跳转到file.html
	 * @return
	 * @throws IOException 
	 */
	@PostMapping("/upload")
	public String file(@RequestParam("file") MultipartFile file) throws IOException {
		File newFile = new File(file.getOriginalFilename());
		String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		if (!(Objects.equals(substring, "jpg") || Objects.equals(substring, "png"))) {
			return "文件格式不对，只能接受jpg、png格式，请重新上传";
		}
		BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFile));
		outputStream.write(file.getBytes());
		outputStream.flush();
		outputStream.close();
		return "file upload success";
	}
	
	@PostMapping("/uploads")
	public String uploadFiles(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
		Iterator<MultipartFile> iterator = files.iterator();
		while (iterator.hasNext()) {
			MultipartFile file = iterator.next();
			File newFile = new File(file.getOriginalFilename());
			BufferedOutputStream outputStream = null;
			try {
				outputStream = new BufferedOutputStream(new FileOutputStream(newFile));
				outputStream.write(file.getBytes());
				outputStream.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return "file upload error";
			} catch (IOException e) {
				e.printStackTrace();
				return "file upload error";
			} finally {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "file upload success";
	}
	
}